home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / email / message.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  29.7 KB  |  793 lines

  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4.  
  5. """Basic message object for the email package object model."""
  6.  
  7. __all__ = ['Message']
  8.  
  9. import re
  10. import uu
  11. import binascii
  12. import warnings
  13. from cStringIO import StringIO
  14.  
  15. # Intrapackage imports
  16. import email.charset
  17. from email import utils
  18. from email import errors
  19.  
  20. SEMISPACE = '; '
  21.  
  22. # Regular expression that matches `special' characters in parameters, the
  23. # existence of which force quoting of the parameter value.
  24. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]')
  25.  
  26.  
  27. # Helper functions
  28. def _splitparam(param):
  29.     # Split header parameters.  BAW: this may be too simple.  It isn't
  30.     # strictly RFC 2045 (section 5.1) compliant, but it catches most headers
  31.     # found in the wild.  We may eventually need a full fledged parser
  32.     # eventually.
  33.     a, sep, b = param.partition(';')
  34.     if not sep:
  35.         return a.strip(), None
  36.     return a.strip(), b.strip()
  37.  
  38. def _formatparam(param, value=None, quote=True):
  39.     """Convenience function to format and return a key=value pair.
  40.  
  41.     This will quote the value if needed or if quote is true.
  42.     """
  43.     if value is not None and len(value) > 0:
  44.         # A tuple is used for RFC 2231 encoded parameter values where items
  45.         # are (charset, language, value).  charset is a string, not a Charset
  46.         # instance.
  47.         if isinstance(value, tuple):
  48.             # Encode as per RFC 2231
  49.             param += '*'
  50.             value = utils.encode_rfc2231(value[2], value[0], value[1])
  51.         # BAW: Please check this.  I think that if quote is set it should
  52.         # force quoting even if not necessary.
  53.         if quote or tspecials.search(value):
  54.             return '%s="%s"' % (param, utils.quote(value))
  55.         else:
  56.             return '%s=%s' % (param, value)
  57.     else:
  58.         return param
  59.  
  60. def _parseparam(s):
  61.     plist = []
  62.     while s[:1] == ';':
  63.         s = s[1:]
  64.         end = s.find(';')
  65.         while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
  66.             end = s.find(';', end + 1)
  67.         if end < 0:
  68.             end = len(s)
  69.         f = s[:end]
  70.         if '=' in f:
  71.             i = f.index('=')
  72.             f = f[:i].strip().lower() + '=' + f[i+1:].strip()
  73.         plist.append(f.strip())
  74.         s = s[end:]
  75.     return plist
  76.  
  77.  
  78. def _unquotevalue(value):
  79.     # This is different than utils.collapse_rfc2231_value() because it doesn't
  80.     # try to convert the value to a unicode.  Message.get_param() and
  81.     # Message.get_params() are both currently defined to return the tuple in
  82.     # the face of RFC 2231 parameters.
  83.     if isinstance(value, tuple):
  84.         return value[0], value[1], utils.unquote(value[2])
  85.     else:
  86.         return utils.unquote(value)
  87.  
  88.  
  89.  
  90. class Message:
  91.     """Basic message object.
  92.  
  93.     A message object is defined as something that has a bunch of RFC 2822
  94.     headers and a payload.  It may optionally have an envelope header
  95.     (a.k.a. Unix-From or From_ header).  If the message is a container (i.e. a
  96.     multipart or a message/rfc822), then the payload is a list of Message
  97.     objects, otherwise it is a string.
  98.  
  99.     Message objects implement part of the `mapping' interface, which assumes
  100.     there is exactly one occurrance of the header per message.  Some headers
  101.     do in fact appear multiple times (e.g. Received) and for those headers,
  102.     you must use the explicit API to set or get all the headers.  Not all of
  103.     the mapping methods are implemented.
  104.     """
  105.     def __init__(self):
  106.         self._headers = []
  107.         self._unixfrom = None
  108.         self._payload = None
  109.         self._charset = None
  110.         # Defaults for multipart messages
  111.         self.preamble = self.epilogue = None
  112.         self.defects = []
  113.         # Default content type
  114.         self._default_type = 'text/plain'
  115.  
  116.     def __str__(self):
  117.         """Return the entire formatted message as a string.
  118.         This includes the headers, body, and envelope header.
  119.         """
  120.         return self.as_string(unixfrom=True)
  121.  
  122.     def as_string(self, unixfrom=False):
  123.         """Return the entire formatted message as a string.
  124.         Optional `unixfrom' when True, means include the Unix From_ envelope
  125.         header.
  126.  
  127.         This is a convenience method and may not generate the message exactly
  128.         as you intend because by default it mangles lines that begin with
  129.         "From ".  For more flexibility, use the flatten() method of a
  130.         Generator instance.
  131.         """
  132.         from email.generator import Generator
  133.         fp = StringIO()
  134.         g = Generator(fp)
  135.         g.flatten(self, unixfrom=unixfrom)
  136.         return fp.getvalue()
  137.  
  138.     def is_multipart(self):
  139.         """Return True if the message consists of multiple parts."""
  140.         return isinstance(self._payload, list)
  141.  
  142.     #
  143.     # Unix From_ line
  144.     #
  145.     def set_unixfrom(self, unixfrom):
  146.         self._unixfrom = unixfrom
  147.  
  148.     def get_unixfrom(self):
  149.         return self._unixfrom
  150.  
  151.     #
  152.     # Payload manipulation.
  153.     #
  154.     def attach(self, payload):
  155.         """Add the given payload to the current payload.
  156.  
  157.         The current payload will always be a list of objects after this method
  158.         is called.  If you want to set the payload to a scalar object, use
  159.         set_payload() instead.
  160.         """
  161.         if self._payload is None:
  162.             self._payload = [payload]
  163.         else:
  164.             self._payload.append(payload)
  165.  
  166.     def get_payload(self, i=None, decode=False):
  167.         """Return a reference to the payload.
  168.  
  169.         The payload will either be a list object or a string.  If you mutate
  170.         the list object, you modify the message's payload in place.  Optional
  171.         i returns that index into the payload.
  172.  
  173.         Optional decode is a flag indicating whether the payload should be
  174.         decoded or not, according to the Content-Transfer-Encoding header
  175.         (default is False).
  176.  
  177.         When True and the message is not a multipart, the payload will be
  178.         decoded if this header's value is `quoted-printable' or `base64'.  If
  179.         some other encoding is used, or the header is missing, or if the
  180.         payload has bogus data (i.e. bogus base64 or uuencoded data), the
  181.         payload is returned as-is.
  182.  
  183.         If the message is a multipart and the decode flag is True, then None
  184.         is returned.
  185.         """
  186.         if i is None:
  187.             payload = self._payload
  188.         elif not isinstance(self._payload, list):
  189.             raise TypeError('Expected list, got %s' % type(self._payload))
  190.         else:
  191.             payload = self._payload[i]
  192.         if decode:
  193.             if self.is_multipart():
  194.                 return None
  195.             cte = self.get('content-transfer-encoding', '').lower()
  196.             if cte == 'quoted-printable':
  197.                 return utils._qdecode(payload)
  198.             elif cte == 'base64':
  199.                 try:
  200.                     return utils._bdecode(payload)
  201.                 except binascii.Error:
  202.                     # Incorrect padding
  203.                     return payload
  204.             elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
  205.                 sfp = StringIO()
  206.                 try:
  207.                     uu.decode(StringIO(payload+'\n'), sfp, quiet=True)
  208.                     payload = sfp.getvalue()
  209.                 except uu.Error:
  210.                     # Some decoding problem
  211.                     return payload
  212.         # Everything else, including encodings with 8bit or 7bit are returned
  213.         # unchanged.
  214.         return payload
  215.  
  216.     def set_payload(self, payload, charset=None):
  217.         """Set the payload to the given value.
  218.  
  219.         Optional charset sets the message's default character set.  See
  220.         set_charset() for details.
  221.         """
  222.         self._payload = payload
  223.         if charset is not None:
  224.             self.set_charset(charset)
  225.  
  226.     def set_charset(self, charset):
  227.         """Set the charset of the payload to a given character set.
  228.  
  229.         charset can be a Charset instance, a string naming a character set, or
  230.         None.  If it is a string it will be converted to a Charset instance.
  231.         If charset is None, the charset parameter will be removed from the
  232.         Content-Type field.  Anything else will generate a TypeError.
  233.  
  234.         The message will be assumed to be of type text/* encoded with
  235.         charset.input_charset.  It will be converted to charset.output_charset
  236.         and encoded properly, if needed, when generating the plain text
  237.         representation of the message.  MIME headers (MIME-Version,
  238.         Content-Type, Content-Transfer-Encoding) will be added as needed.
  239.  
  240.         """
  241.         if charset is None:
  242.             self.del_param('charset')
  243.             self._charset = None
  244.             return
  245.         if isinstance(charset, basestring):
  246.             charset = email.charset.Charset(charset)
  247.         if not isinstance(charset, email.charset.Charset):
  248.             raise TypeError(charset)
  249.         # BAW: should we accept strings that can serve as arguments to the
  250.         # Charset constructor?
  251.         self._charset = charset
  252.         if not self.has_key('MIME-Version'):
  253.             self.add_header('MIME-Version', '1.0')
  254.         if not self.has_key('Content-Type'):
  255.             self.add_header('Content-Type', 'text/plain',
  256.                             charset=charset.get_output_charset())
  257.         else:
  258.             self.set_param('charset', charset.get_output_charset())
  259.         if isinstance(self._payload, unicode):
  260.             self._payload = self._payload.encode(charset.output_charset)
  261.         if str(charset) != charset.get_output_charset():
  262.             self._payload = charset.body_encode(self._payload)
  263.         if not self.has_key('Content-Transfer-Encoding'):
  264.             cte = charset.get_body_encoding()
  265.             try:
  266.                 cte(self)
  267.             except TypeError:
  268.                 self._payload = charset.body_encode(self._payload)
  269.                 self.add_header('Content-Transfer-Encoding', cte)
  270.  
  271.     def get_charset(self):
  272.         """Return the Charset instance associated with the message's payload.
  273.         """
  274.         return self._charset
  275.  
  276.     #
  277.     # MAPPING INTERFACE (partial)
  278.     #
  279.     def __len__(self):
  280.         """Return the total number of headers, including duplicates."""
  281.         return len(self._headers)
  282.  
  283.     def __getitem__(self, name):
  284.         """Get a header value.
  285.  
  286.         Return None if the header is missing instead of raising an exception.
  287.  
  288.         Note that if the header appeared multiple times, exactly which
  289.         occurrance gets returned is undefined.  Use get_all() to get all
  290.         the values matching a header field name.
  291.         """
  292.         return self.get(name)
  293.  
  294.     def __setitem__(self, name, val):
  295.         """Set the value of a header.
  296.  
  297.         Note: this does not overwrite an existing header with the same field
  298.         name.  Use __delitem__() first to delete any existing headers.
  299.         """
  300.         self._headers.append((name, val))
  301.  
  302.     def __delitem__(self, name):
  303.         """Delete all occurrences of a header, if present.
  304.  
  305.         Does not raise an exception if the header is missing.
  306.         """
  307.         name = name.lower()
  308.         newheaders = []
  309.         for k, v in self._headers:
  310.             if k.lower() != name:
  311.                 newheaders.append((k, v))
  312.         self._headers = newheaders
  313.  
  314.     def __contains__(self, name):
  315.         return name.lower() in [k.lower() for k, v in self._headers]
  316.  
  317.     def has_key(self, name):
  318.         """Return true if the message contains the header."""
  319.         missing = object()
  320.         return self.get(name, missing) is not missing
  321.  
  322.     def keys(self):
  323.         """Return a list of all the message's header field names.
  324.  
  325.         These will be sorted in the order they appeared in the original
  326.         message, or were added to the message, and may contain duplicates.
  327.         Any fields deleted and re-inserted are always appended to the header
  328.         list.
  329.         """
  330.         return [k for k, v in self._headers]
  331.  
  332.     def values(self):
  333.         """Return a list of all the message's header values.
  334.  
  335.         These will be sorted in the order they appeared in the original
  336.         message, or were added to the message, and may contain duplicates.
  337.         Any fields deleted and re-inserted are always appended to the header
  338.         list.
  339.         """
  340.         return [v for k, v in self._headers]
  341.  
  342.     def items(self):
  343.         """Get all the message's header fields and values.
  344.  
  345.         These will be sorted in the order they appeared in the original
  346.         message, or were added to the message, and may contain duplicates.
  347.         Any fields deleted and re-inserted are always appended to the header
  348.         list.
  349.         """
  350.         return self._headers[:]
  351.  
  352.     def get(self, name, failobj=None):
  353.         """Get a header value.
  354.  
  355.         Like __getitem__() but return failobj instead of None when the field
  356.         is missing.
  357.         """
  358.         name = name.lower()
  359.         for k, v in self._headers:
  360.             if k.lower() == name:
  361.                 return v
  362.         return failobj
  363.  
  364.     #
  365.     # Additional useful stuff
  366.     #
  367.  
  368.     def get_all(self, name, failobj=None):
  369.         """Return a list of all the values for the named field.
  370.  
  371.         These will be sorted in the order they appeared in the original
  372.         message, and may contain duplicates.  Any fields deleted and
  373.         re-inserted are always appended to the header list.
  374.  
  375.         If no such fields exist, failobj is returned (defaults to None).
  376.         """
  377.         values = []
  378.         name = name.lower()
  379.         for k, v in self._headers:
  380.             if k.lower() == name:
  381.                 values.append(v)
  382.         if not values:
  383.             return failobj
  384.         return values
  385.  
  386.     def add_header(self, _name, _value, **_params):
  387.         """Extended header setting.
  388.  
  389.         name is the header field to add.  keyword arguments can be used to set
  390.         additional parameters for the header field, with underscores converted
  391.         to dashes.  Normally the parameter will be added as key="value" unless
  392.         value is None, in which case only the key will be added.
  393.  
  394.         Example:
  395.  
  396.         msg.add_header('content-disposition', 'attachment', filename='bud.gif')
  397.         """
  398.         parts = []
  399.         for k, v in _params.items():
  400.             if v is None:
  401.                 parts.append(k.replace('_', '-'))
  402.             else:
  403.                 parts.append(_formatparam(k.replace('_', '-'), v))
  404.         if _value is not None:
  405.             parts.insert(0, _value)
  406.         self._headers.append((_name, SEMISPACE.join(parts)))
  407.  
  408.     def replace_header(self, _name, _value):
  409.         """Replace a header.
  410.  
  411.         Replace the first matching header found in the message, retaining
  412.         header order and case.  If no matching header was found, a KeyError is
  413.         raised.
  414.         """
  415.         _name = _name.lower()
  416.         for i, (k, v) in zip(range(len(self._headers)), self._headers):
  417.             if k.lower() == _name:
  418.                 self._headers[i] = (k, _value)
  419.                 break
  420.         else:
  421.             raise KeyError(_name)
  422.  
  423.     #
  424.     # Use these three methods instead of the three above.
  425.     #
  426.  
  427.     def get_content_type(self):
  428.         """Return the message's content type.
  429.  
  430.         The returned string is coerced to lower case of the form
  431.         `maintype/subtype'.  If there was no Content-Type header in the
  432.         message, the default type as given by get_default_type() will be
  433.         returned.  Since according to RFC 2045, messages always have a default
  434.         type this will always return a value.
  435.  
  436.         RFC 2045 defines a message's default type to be text/plain unless it
  437.         appears inside a multipart/digest container, in which case it would be
  438.         message/rfc822.
  439.         """
  440.         missing = object()
  441.         value = self.get('content-type', missing)
  442.         if value is missing:
  443.             # This should have no parameters
  444.             return self.get_default_type()
  445.         ctype = _splitparam(value)[0].lower()
  446.         # RFC 2045, section 5.2 says if its invalid, use text/plain
  447.         if ctype.count('/') != 1:
  448.             return 'text/plain'
  449.         return ctype
  450.  
  451.     def get_content_maintype(self):
  452.         """Return the message's main content type.
  453.  
  454.         This is the `maintype' part of the string returned by
  455.         get_content_type().
  456.         """
  457.         ctype = self.get_content_type()
  458.         return ctype.split('/')[0]
  459.  
  460.     def get_content_subtype(self):
  461.         """Returns the message's sub-content type.
  462.  
  463.         This is the `subtype' part of the string returned by
  464.         get_content_type().
  465.         """
  466.         ctype = self.get_content_type()
  467.         return ctype.split('/')[1]
  468.  
  469.     def get_default_type(self):
  470.         """Return the `default' content type.
  471.  
  472.         Most messages have a default content type of text/plain, except for
  473.         messages that are subparts of multipart/digest containers.  Such
  474.         subparts have a default content type of message/rfc822.
  475.         """
  476.         return self._default_type
  477.  
  478.     def set_default_type(self, ctype):
  479.         """Set the `default' content type.
  480.  
  481.         ctype should be either "text/plain" or "message/rfc822", although this
  482.         is not enforced.  The default content type is not stored in the
  483.         Content-Type header.
  484.         """
  485.         self._default_type = ctype
  486.  
  487.     def _get_params_preserve(self, failobj, header):
  488.         # Like get_params() but preserves the quoting of values.  BAW:
  489.         # should this be part of the public interface?
  490.         missing = object()
  491.         value = self.get(header, missing)
  492.         if value is missing:
  493.             return failobj
  494.         params = []
  495.         for p in _parseparam(';' + value):
  496.             try:
  497.                 name, val = p.split('=', 1)
  498.                 name = name.strip()
  499.                 val = val.strip()
  500.             except ValueError:
  501.                 # Must have been a bare attribute
  502.                 name = p.strip()
  503.                 val = ''
  504.             params.append((name, val))
  505.         params = utils.decode_params(params)
  506.         return params
  507.  
  508.     def get_params(self, failobj=None, header='content-type', unquote=True):
  509.         """Return the message's Content-Type parameters, as a list.
  510.  
  511.         The elements of the returned list are 2-tuples of key/value pairs, as
  512.         split on the `=' sign.  The left hand side of the `=' is the key,
  513.         while the right hand side is the value.  If there is no `=' sign in
  514.         the parameter the value is the empty string.  The value is as
  515.         described in the get_param() method.
  516.  
  517.         Optional failobj is the object to return if there is no Content-Type
  518.         header.  Optional header is the header to search instead of
  519.         Content-Type.  If unquote is True, the value is unquoted.
  520.         """
  521.         missing = object()
  522.         params = self._get_params_preserve(missing, header)
  523.         if params is missing:
  524.             return failobj
  525.         if unquote:
  526.             return [(k, _unquotevalue(v)) for k, v in params]
  527.         else:
  528.             return params
  529.  
  530.     def get_param(self, param, failobj=None, header='content-type',
  531.                   unquote=True):
  532.         """Return the parameter value if found in the Content-Type header.
  533.  
  534.         Optional failobj is the object to return if there is no Content-Type
  535.         header, or the Content-Type header has no such parameter.  Optional
  536.         header is the header to search instead of Content-Type.
  537.  
  538.         Parameter keys are always compared case insensitively.  The return
  539.         value can either be a string, or a 3-tuple if the parameter was RFC
  540.         2231 encoded.  When it's a 3-tuple, the elements of the value are of
  541.         the form (CHARSET, LANGUAGE, VALUE).  Note that both CHARSET and
  542.         LANGUAGE can be None, in which case you should consider VALUE to be
  543.         encoded in the us-ascii charset.  You can usually ignore LANGUAGE.
  544.  
  545.         Your application should be prepared to deal with 3-tuple return
  546.         values, and can convert the parameter to a Unicode string like so:
  547.  
  548.             param = msg.get_param('foo')
  549.             if isinstance(param, tuple):
  550.                 param = unicode(param[2], param[0] or 'us-ascii')
  551.  
  552.         In any case, the parameter value (either the returned string, or the
  553.         VALUE item in the 3-tuple) is always unquoted, unless unquote is set
  554.         to False.
  555.         """
  556.         if not self.has_key(header):
  557.             return failobj
  558.         for k, v in self._get_params_preserve(failobj, header):
  559.             if k.lower() == param.lower():
  560.                 if unquote:
  561.                     return _unquotevalue(v)
  562.                 else:
  563.                     return v
  564.         return failobj
  565.  
  566.     def set_param(self, param, value, header='Content-Type', requote=True,
  567.                   charset=None, language=''):
  568.         """Set a parameter in the Content-Type header.
  569.  
  570.         If the parameter already exists in the header, its value will be
  571.         replaced with the new value.
  572.  
  573.         If header is Content-Type and has not yet been defined for this
  574.         message, it will be set to "text/plain" and the new parameter and
  575.         value will be appended as per RFC 2045.
  576.  
  577.         An alternate header can specified in the header argument, and all
  578.         parameters will be quoted as necessary unless requote is False.
  579.  
  580.         If charset is specified, the parameter will be encoded according to RFC
  581.         2231.  Optional language specifies the RFC 2231 language, defaulting
  582.         to the empty string.  Both charset and language should be strings.
  583.         """
  584.         if not isinstance(value, tuple) and charset:
  585.             value = (charset, language, value)
  586.  
  587.         if not self.has_key(header) and header.lower() == 'content-type':
  588.             ctype = 'text/plain'
  589.         else:
  590.             ctype = self.get(header)
  591.         if not self.get_param(param, header=header):
  592.             if not ctype:
  593.                 ctype = _formatparam(param, value, requote)
  594.             else:
  595.                 ctype = SEMISPACE.join(
  596.                     [ctype, _formatparam(param, value, requote)])
  597.         else:
  598.             ctype = ''
  599.             for old_param, old_value in self.get_params(header=header,
  600.                                                         unquote=requote):
  601.                 append_param = ''
  602.                 if old_param.lower() == param.lower():
  603.                     append_param = _formatparam(param, value, requote)
  604.                 else:
  605.                     append_param = _formatparam(old_param, old_value, requote)
  606.                 if not ctype:
  607.                     ctype = append_param
  608.                 else:
  609.                     ctype = SEMISPACE.join([ctype, append_param])
  610.         if ctype != self.get(header):
  611.             del self[header]
  612.             self[header] = ctype
  613.  
  614.     def del_param(self, param, header='content-type', requote=True):
  615.         """Remove the given parameter completely from the Content-Type header.
  616.  
  617.         The header will be re-written in place without the parameter or its
  618.         value. All values will be quoted as necessary unless requote is
  619.         False.  Optional header specifies an alternative to the Content-Type
  620.         header.
  621.         """
  622.         if not self.has_key(header):
  623.             return
  624.         new_ctype = ''
  625.         for p, v in self.get_params(header=header, unquote=requote):
  626.             if p.lower() != param.lower():
  627.                 if not new_ctype:
  628.                     new_ctype = _formatparam(p, v, requote)
  629.                 else:
  630.                     new_ctype = SEMISPACE.join([new_ctype,
  631.                                                 _formatparam(p, v, requote)])
  632.         if new_ctype != self.get(header):
  633.             del self[header]
  634.             self[header] = new_ctype
  635.  
  636.     def set_type(self, type, header='Content-Type', requote=True):
  637.         """Set the main type and subtype for the Content-Type header.
  638.  
  639.         type must be a string in the form "maintype/subtype", otherwise a
  640.         ValueError is raised.
  641.  
  642.         This method replaces the Content-Type header, keeping all the
  643.         parameters in place.  If requote is False, this leaves the existing
  644.         header's quoting as is.  Otherwise, the parameters will be quoted (the
  645.         default).
  646.  
  647.         An alternative header can be specified in the header argument.  When
  648.         the Content-Type header is set, we'll always also add a MIME-Version
  649.         header.
  650.         """
  651.         # BAW: should we be strict?
  652.         if not type.count('/') == 1:
  653.             raise ValueError
  654.         # Set the Content-Type, you get a MIME-Version
  655.         if header.lower() == 'content-type':
  656.             del self['mime-version']
  657.             self['MIME-Version'] = '1.0'
  658.         if not self.has_key(header):
  659.             self[header] = type
  660.             return
  661.         params = self.get_params(header=header, unquote=requote)
  662.         del self[header]
  663.         self[header] = type
  664.         # Skip the first param; it's the old type.
  665.         for p, v in params[1:]:
  666.             self.set_param(p, v, header, requote)
  667.  
  668.     def get_filename(self, failobj=None):
  669.         """Return the filename associated with the payload if present.
  670.  
  671.         The filename is extracted from the Content-Disposition header's
  672.         `filename' parameter, and it is unquoted.  If that header is missing
  673.         the `filename' parameter, this method falls back to looking for the
  674.         `name' parameter.
  675.         """
  676.         missing = object()
  677.         filename = self.get_param('filename', missing, 'content-disposition')
  678.         if filename is missing:
  679.             filename = self.get_param('name', missing, 'content-type')
  680.         if filename is missing:
  681.             return failobj
  682.         return utils.collapse_rfc2231_value(filename).strip()
  683.  
  684.     def get_boundary(self, failobj=None):
  685.         """Return the boundary associated with the payload if present.
  686.  
  687.         The boundary is extracted from the Content-Type header's `boundary'
  688.         parameter, and it is unquoted.
  689.         """
  690.         missing = object()
  691.         boundary = self.get_param('boundary', missing)
  692.         if boundary is missing:
  693.             return failobj
  694.         # RFC 2046 says that boundaries may begin but not end in w/s
  695.         return utils.collapse_rfc2231_value(boundary).rstrip()
  696.  
  697.     def set_boundary(self, boundary):
  698.         """Set the boundary parameter in Content-Type to 'boundary'.
  699.  
  700.         This is subtly different than deleting the Content-Type header and
  701.         adding a new one with a new boundary parameter via add_header().  The
  702.         main difference is that using the set_boundary() method preserves the
  703.         order of the Content-Type header in the original message.
  704.  
  705.         HeaderParseError is raised if the message has no Content-Type header.
  706.         """
  707.         missing = object()
  708.         params = self._get_params_preserve(missing, 'content-type')
  709.         if params is missing:
  710.             # There was no Content-Type header, and we don't know what type
  711.             # to set it to, so raise an exception.
  712.             raise errors.HeaderParseError('No Content-Type header found')
  713.         newparams = []
  714.         foundp = False
  715.         for pk, pv in params:
  716.             if pk.lower() == 'boundary':
  717.                 newparams.append(('boundary', '"%s"' % boundary))
  718.                 foundp = True
  719.             else:
  720.                 newparams.append((pk, pv))
  721.         if not foundp:
  722.             # The original Content-Type header had no boundary attribute.
  723.             # Tack one on the end.  BAW: should we raise an exception
  724.             # instead???
  725.             newparams.append(('boundary', '"%s"' % boundary))
  726.         # Replace the existing Content-Type header with the new value
  727.         newheaders = []
  728.         for h, v in self._headers:
  729.             if h.lower() == 'content-type':
  730.                 parts = []
  731.                 for k, v in newparams:
  732.                     if v == '':
  733.                         parts.append(k)
  734.                     else:
  735.                         parts.append('%s=%s' % (k, v))
  736.                 newheaders.append((h, SEMISPACE.join(parts)))
  737.  
  738.             else:
  739.                 newheaders.append((h, v))
  740.         self._headers = newheaders
  741.  
  742.     def get_content_charset(self, failobj=None):
  743.         """Return the charset parameter of the Content-Type header.
  744.  
  745.         The returned string is always coerced to lower case.  If there is no
  746.         Content-Type header, or if that header has no charset parameter,
  747.         failobj is returned.
  748.         """
  749.         missing = object()
  750.         charset = self.get_param('charset', missing)
  751.         if charset is missing:
  752.             return failobj
  753.         if isinstance(charset, tuple):
  754.             # RFC 2231 encoded, so decode it, and it better end up as ascii.
  755.             pcharset = charset[0] or 'us-ascii'
  756.             try:
  757.                 # LookupError will be raised if the charset isn't known to
  758.                 # Python.  UnicodeError will be raised if the encoded text
  759.                 # contains a character not in the charset.
  760.                 charset = unicode(charset[2], pcharset).encode('us-ascii')
  761.             except (LookupError, UnicodeError):
  762.                 charset = charset[2]
  763.         # charset character must be in us-ascii range
  764.         try:
  765.             if isinstance(charset, str):
  766.                 charset = unicode(charset, 'us-ascii')
  767.             charset = charset.encode('us-ascii')
  768.         except UnicodeError:
  769.             return failobj
  770.         # RFC 2046, $4.1.2 says charsets are not case sensitive
  771.         return charset.lower()
  772.  
  773.     def get_charsets(self, failobj=None):
  774.         """Return a list containing the charset(s) used in this message.
  775.  
  776.         The returned list of items describes the Content-Type headers'
  777.         charset parameter for this message and all the subparts in its
  778.         payload.
  779.  
  780.         Each item will either be a string (the value of the charset parameter
  781.         in the Content-Type header of that part) or the value of the
  782.         'failobj' parameter (defaults to None), if the part does not have a
  783.         main MIME type of "text", or the charset is not defined.
  784.  
  785.         The list will contain one string for each part of the message, plus
  786.         one for the container message (i.e. self), so that a non-multipart
  787.         message will still return a list of length 1.
  788.         """
  789.         return [part.get_content_charset(failobj) for part in self.walk()]
  790.  
  791.     # I.e. def walk(self): ...
  792.     from email.iterators import walk
  793.